<template>
	<view class="login-container">
		<!-- 蓝色背景区域 -->
		<view class="header-section">
			<view class="welcome-text">
				<text class="greeting">您好,</text>
				<text class="welcome">欢迎登录车联网服务!</text>
			</view>
			<view class="illustration">
				<image src="/static/login/组 6.png" class="character-car" mode="aspectFit"></image>
			</view>
		</view>
		
		<!-- 白色表单区域 -->
		<view class="form-section">
			<view class="form-container">
				<!-- 手机号输入框 -->
				<view class="input-group">
					<uni-easyinput 
						v-model="phoneNumber" 
						placeholder="请输入手机号"
						:clearable="true"
						:maxlength="11"
						type="number"
						class="phone-input"
						:class="{ 'error': phoneError }"
					></uni-easyinput>
					<view v-if="phoneError" class="error-text">{{ phoneError }}</view>
				</view>
				
				<!-- 验证码输入框 -->
				<view class="input-group">
					<view class="code-input-wrapper">
						<uni-easyinput 
							v-model="verificationCode" 
							placeholder="请输入验证码"
							:clearable="true"
							:maxlength="6"
							type="number"
							class="code-input"
							:class="{ 'error': codeError }"
						></uni-easyinput>
						<button 
							class="get-code-btn" 
							:disabled="!canGetCode"
							@click="getVerificationCode"
						>
							{{ codeButtonText }}
						</button>
					</view>
					<view v-if="codeError" class="error-text">{{ codeError }}</view>
				</view>
				
				<!-- 登录按钮 -->
				<button 
					class="login-btn" 
					:disabled="!canLogin"
					@click="handleLogin"
				>
					<text v-if="isLoading">登录中...</text>
					<text v-else>登录</text>
				</button>
			</view>
		</view>
		
		<!-- 位置权限申请弹窗 -->
		<uni-popup ref="locationPopup" type="bottom" :mask-click="false">
			<view class="location-permission-popup">
				<view class="popup-content">
					<view class="popup-title">获取你的位置信息</view>
					<view class="popup-desc">你的位置信息将用于获取你附近的站点</view>
					<view class="popup-buttons">
						<button class="reject-btn" @click="rejectLocation">拒绝</button>
						<button class="allow-btn" @click="allowLocation">允许</button>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import authManager from '../../utils/auth.js'
	import { post } from '../../utils/api.js'
	
	export default {
		data() {
			return {
				phoneNumber: '',
				verificationCode: '',
				countdown: 0,
				timer: null,
				locationInfo: null,
				hasLocationPermission: false,
				isLoading: false,
				phoneError: '',
				codeError: ''
			}
		},
		computed: {
			canGetCode() {
				return this.validatePhone(this.phoneNumber) && this.countdown === 0 && !this.isLoading
			},
			canLogin() {
				return this.validatePhone(this.phoneNumber) && this.verificationCode.length === 6 && !this.isLoading
			},
			codeButtonText() {
				return this.countdown > 0 ? `${this.countdown}s后重新获取` : '获取验证码'
			}
		},
		onLoad() {
			// 页面加载时检查位置权限
			this.checkLocationPermission()
			// 检查是否已登录
			this.checkLoginStatus()
		},
		
		methods: {
			// 检查登录状态
			checkLoginStatus() {
				if (authManager.checkLogin()) {
					// 已登录，跳转到首页
					uni.reLaunch({
						url: '/pages/index/index'
					})
				}
			},
			
			// 手机号格式验证
			validatePhone(phoneNumber) {
				const phoneRegex = /^1[3-9]\d{9}$/
				return phoneRegex.test(phoneNumber)
			},
			
			// 检查位置权限
			checkLocationPermission() {
				// 检查是否已经获取过位置权限
				const locationPermission = uni.getStorageSync('locationPermission')
				if (locationPermission === 'granted') {
					this.hasLocationPermission = true
					this.getCurrentLocation()
					return
				}
				
				// 延迟显示弹窗，让页面先渲染完成
				setTimeout(() => {
					this.$refs.locationPopup.open()
				}, 500)
			},
			
			// 允许获取位置
			allowLocation() {
				this.$refs.locationPopup.close()
				this.getCurrentLocation()
			},
			
			// 拒绝获取位置
			rejectLocation() {
				this.$refs.locationPopup.close()
				uni.setStorageSync('locationPermission', 'denied')
				uni.showToast({
					title: '已拒绝位置权限',
					icon: 'none'
				})
			},
			
			// 获取当前位置
			getCurrentLocation() {
				uni.showLoading({
					title: '获取位置中...'
				})
				
				uni.getLocation({
					type: 'gcj02',
					altitude: true,
					success: (res) => {
						uni.hideLoading()
						this.locationInfo = {
							latitude: res.latitude,
							longitude: res.longitude,
							altitude: res.altitude,
							accuracy: res.accuracy
						}
						
						// 保存权限状态
						uni.setStorageSync('locationPermission', 'granted')
						this.hasLocationPermission = true
						
						// 获取地址信息
						this.getAddressFromLocation(res.latitude, res.longitude)
						
						uni.showToast({
							title: '位置获取成功',
							icon: 'success'
						})
					},
					fail: (err) => {
						uni.hideLoading()
						console.error('获取位置失败:', err)
						
						if (err.errMsg.includes('auth deny')) {
							uni.showToast({
								title: '位置权限被拒绝',
								icon: 'none'
							})
						} else {
							uni.showToast({
								title: '获取位置失败',
								icon: 'none'
							})
						}
					}
				})
			},
			
			// 根据坐标获取地址信息
			getAddressFromLocation(latitude, longitude) {
				// 这里可以调用地图API进行逆地理编码
				// 由于需要API密钥，这里先模拟数据
				console.log('获取地址信息:', { latitude, longitude })
				
				// 模拟获取到的地址信息
				this.locationInfo.address = '北京市朝阳区'
				this.locationInfo.city = '北京市'
				
				// 保存位置信息到本地存储
				uni.setStorageSync('userLocation', this.locationInfo)
			},
			
			// 获取验证码
			async getVerificationCode() {
				if (!this.canGetCode) return
				
				// 清除之前的错误信息
				this.phoneError = ''
				this.codeError = ''
				
				// 验证手机号格式
				if (!this.validatePhone(this.phoneNumber)) {
					this.phoneError = '请输入正确的手机号'
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					})
					return
				}
				
				try {
					this.isLoading = true
					
					// 调用发送验证码接口
					await post('/user/sms/send', {
						phone: this.phoneNumber
					})
					
					// 开始倒计时
					this.countdown = 60
					this.timer = setInterval(() => {
						this.countdown--
						if (this.countdown <= 0) {
							clearInterval(this.timer)
							this.timer = null
						}
					}, 1000)
					
					uni.showToast({
						title: '验证码已发送',
						icon: 'success'
					})
				} catch (error) {
					console.error('发送验证码失败:', error)
					uni.showToast({
						title: error.message || '发送失败，请重试',
						icon: 'none'
					})
				} finally {
					this.isLoading = false
				}
			},
			
			// 重新获取位置
			refreshLocation() {
				if (!this.hasLocationPermission) {
					this.$refs.locationPopup.open()
					return
				}
				this.getCurrentLocation()
			},
			
			// 登录
			async handleLogin() {
				if (!this.canLogin) return
				
				// 清除之前的错误信息
				this.phoneError = ''
				this.codeError = ''
				
				// 验证手机号格式
				if (!this.validatePhone(this.phoneNumber)) {
					this.phoneError = '请输入正确的手机号'
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					})
					return
				}
				
				// 验证验证码
				if (this.verificationCode.length !== 6) {
					this.codeError = '请输入6位验证码'
					uni.showToast({
						title: '请输入6位验证码',
						icon: 'none'
					})
					return
				}
				
				try {
					this.isLoading = true
					uni.showLoading({
						title: '登录中...'
					})
					
					// 调用登录接口
					const response = await post('/user/sms/login', {
						phone: this.phoneNumber,
						code: this.verificationCode
					})
					
					// 保存用户信息
					authManager.saveUserInfo(response.data || response)
					
					uni.hideLoading()
					
					// 登录成功提示
					uni.showToast({
						title: '登录成功',
						icon: 'success'
					})
					
					// 如果是新用户，显示欢迎信息
					const userInfo = authManager.getUserInfo()
					if (userInfo && userInfo.isNewUser) {
						setTimeout(() => {
							uni.showToast({
								title: '欢迎使用车服服务！',
								icon: 'success'
							})
						}, 1500)
					}
					
					// 登录成功后跳转到首页
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/index/index'
						})
					}, 2000)
					
				} catch (error) {
					uni.hideLoading()
					console.error('登录失败:', error)
					
					// 根据错误类型显示不同的提示
					if (error.message.includes('验证码')) {
						this.codeError = error.message
					} else if (error.message.includes('手机号')) {
						this.phoneError = error.message
					}
					
					uni.showToast({
						title: error.message || '登录失败，请重试',
						icon: 'none'
					})
				} finally {
					this.isLoading = false
				}
			}
		},
		
		beforeDestroy() {
			if (this.timer) {
				clearInterval(this.timer)
			}
		}
	}
</script>

<style scoped>
	.login-container {
		width: 100%;
		height: 100vh;
		display: flex;
		flex-direction: column;
		background: #ffffff;
	}
	
	/* 蓝色背景区域 */
	.header-section {
		background: linear-gradient(135deg, #4A90E2 0%, #357ABD 100%);
		position: relative;
		overflow: hidden;
		display: flex;
		align-items: center;
		padding: 60rpx 40rpx 40rpx;
		height: 400rpx;
	}
	
	.header-section::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: url('/static/login/组 8.png') no-repeat;
		background-size: cover;
		background-position: center;
		opacity: 0.2;
		z-index: 1;
	}
	
	.welcome-text {
		flex: 1;
		z-index: 2;
		position: relative;
	}
	
	.greeting {
		display: block;
		color: #ffffff;
		font-size: 36rpx;
		font-weight: 400;
		margin-bottom: 10rpx;
	}
	
	.welcome {
		display: block;
		color: #ffffff;
		font-size: 28rpx;
		font-weight: 300;
		opacity: 0.9;
	}
	
	.illustration {
		width: 240rpx;
		height: 240rpx;
		z-index: 2;
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.character-car {
		width: 100%;
		height: 100%;
		object-fit: contain;
	}
	
	/* 白色表单区域 */
	.form-section {
		background: #ffffff;
		border-radius: 40rpx 40rpx 0 0;
		padding: 60rpx 40rpx 80rpx;
		box-shadow: 0 -10rpx 30rpx rgba(0, 0, 0, 0.1);
		position: relative;
		z-index: 3;
		margin-top: -25rpx;
		flex: 1;
		min-height: calc(100vh - 400rpx + 25rpx);
	}
	
	.form-container {
		max-width: 600rpx;
		margin: 0 auto;
	}
	
	.input-group {
		margin-bottom: 40rpx;
	}
	
	.phone-input {
		background: transparent;
		border-bottom: 2rpx solid #e0e0e0;
		padding: 24rpx 0;
		font-size: 32rpx;
		color: #333333;
	}
	
	.code-input-wrapper {
		display: flex;
		align-items: center;
		border-bottom: 2rpx solid #e0e0e0;
		padding: 24rpx 0;
	}
	
	.code-input {
		flex: 1;
		background: transparent;
		font-size: 32rpx;
		border: none;
		color: #333333;
	}
	
	.get-code-btn {
		background: #4A90E2;
		color: #ffffff;
		border: none;
		border-radius: 8rpx;
		padding: 16rpx 24rpx;
		font-size: 24rpx;
		margin-left: 20rpx;
		min-width: 160rpx;
		height: 60rpx;
		line-height: 60rpx;
	}
	
	.get-code-btn:disabled {
		background: #cccccc;
		color: #999999;
	}
	
	.login-btn {
		width: 100%;
		background: #4A90E2;
		color: #ffffff;
		border: none;
		border-radius: 12rpx;
		padding: 24rpx;
		font-size: 36rpx;
		font-weight: 500;
		margin-top: 60rpx;
		height: 88rpx;
		line-height: 88rpx;
	}
	
	.login-btn:disabled {
		background: #cccccc;
		color: #999999;
	}
	
	/* 输入框聚焦状态 */
	.phone-input:focus,
	.code-input:focus {
		border-bottom-color: #4A90E2;
	}
	
	/* 错误状态样式 */
	.phone-input.error,
	.code-input.error {
		border-bottom-color: #FF3B30;
	}
	
	.error-text {
		color: #FF3B30;
		font-size: 24rpx;
		margin-top: 8rpx;
		line-height: 1.2;
	}
	
	/* 按钮点击效果 */
	.get-code-btn:active,
	.login-btn:active {
		opacity: 0.8;
		transform: scale(0.98);
	}
	
	/* 位置权限弹窗样式 */
	.location-permission-popup {
		background: #f8f8f8;
		border-radius: 20rpx 20rpx 0 0;
		padding: 0;
	}
	
	.popup-content {
		padding: 40rpx 30rpx 30rpx;
	}
	
	.popup-title {
		font-size: 32rpx;
		font-weight: 500;
		color: #333333;
		text-align: center;
		margin-bottom: 20rpx;
	}
	
	.popup-desc {
		font-size: 28rpx;
		color: #666666;
		text-align: center;
		line-height: 1.5;
		margin-bottom: 40rpx;
	}
	
	.popup-buttons {
		display: flex;
		gap: 20rpx;
	}
	
	.reject-btn {
		flex: 1;
		background: #e0e0e0;
		color: #666666;
		border: none;
		border-radius: 8rpx;
		padding: 20rpx;
		font-size: 32rpx;
		height: 80rpx;
		line-height: 80rpx;
	}
	
	.allow-btn {
		flex: 1;
		background: #4A90E2;
		color: #ffffff;
		border: none;
		border-radius: 8rpx;
		padding: 20rpx;
		font-size: 32rpx;
		height: 80rpx;
		line-height: 80rpx;
	}
	
	.reject-btn:active,
	.allow-btn:active {
		opacity: 0.8;
		transform: scale(0.98);
	}
	
	/* 响应式设计 */
	@media screen and (max-width: 750rpx) {
		.header-section {
			padding: 40rpx 30rpx 30rpx;
		}
		
		.illustration {
			width: 200rpx;
			height: 200rpx;
		}
		
		.form-section {
			padding: 50rpx 30rpx 60rpx;
		}
	}
</style>
